<template>
  <div class="upload">
    <van-field
      name="img"
      :label="payload.label || '图片上传'"
      class="mb8"
      clickable
      readonly
      :required="payload.required"
      :rules="payload.rules"
    >
      <template #input>
        <div v-if="fileList.length < payload.count" @click="chooseImage" class="van-uploader__upload">
          <van-icon name="photograph" class="van-uploader__upload-icon" />
        </div>
        <div class="van-uploader__wrapper" v-if="fileList.length">
          <div
            class="van-uploader__preview"
            v-for="img in fileList"
            :key="img"
          >
            <img-preview :imgs="[img]"></img-preview>
            <div class="van-uploader__preview-delete" @click="removeImg(img)">
              <van-icon name="cross" class="van-uploader__preview-delete-icon"></van-icon>
            </div>
          </div>
        </div>
      </template>
    </van-field>
  </div>
</template>

<script>
import { uploadImage } from '@/service/signIn';
import imgPreview from './img-preview.vue';

export default {
  components: { imgPreview },
  name: 'CUpload',
  props: {
    payload: {
      type: Object,
      default: () => ({
        count: 1,
        key: '', // 字段名
      }),
    },
    defaultValue: Object,
  },
  data() {
    return {
      fileList: [],
    };
  },
  watch: {
    defaultValue: {
      deep: true,
      immediate: true,
      handler(obj) {
        const { [this.payload.key]: imgs } = obj;
        let retImgs = imgs;
        if (typeof imgs === 'string') {
          retImgs = imgs ? imgs.split(',') : [];
        }
        if (!retImgs || !retImgs.length) {
          this.fileList = [];
        } else {
          this.fileList = retImgs;
        }
      },
    },
  },
  methods: {
    // 选择照片或者拍照
    chooseImage() {
      wx.chooseImage({
        count: this.payload.count,
        sourceType: ['camera'],
        success: res => {
          const file = res.localIds[0];
          wx.uploadImage({
            localId: file,
            isShowProgressTips: 1,
            success: (res1) => {
              uploadImage([res1.serverId]).then(({ data = [] }) => {
                this.fileList = this.fileList.concat(data);
                this.$emit('cb', this.fileList);
              });
            },
          });
        },
      });
    },
    removeImg(img) {
      this.fileList = this.fileList.filter(file => file !== img);
      this.$emit('cb', this.fileList);
    },
  },
};
</script>
